import copy
import datetime
import json
import threading
import time
import traceback

import pymysql
import requests
import xmltodict as xmltodict
from django.http import HttpResponse
from django.shortcuts import render
import pytz

ACCESS_TOKEN = None
APP_ID = "wxfdcce91cd9433b5e"
APP_SECRET = "9d9c8a0ea8a9ef09ba261d46d4d7ca7f"

conn = pymysql.connect(host="49.232.24.234", port=3306, user="root", passwd="xiwenshujuku123!@#", db="wechat")


def messageHelper(request):
    msg_xml_str = request.body
    if not msg_xml_str:
        return "success"

    # 解析消息
    msg_xml_dict_all = xmltodict.parse(msg_xml_str)
    msg_xml_dict = msg_xml_dict_all["xml"]
    print("解析消息成功", msg_xml_dict)
    # 获取消息类型, 消息内容等信息
    msg_type = msg_xml_dict["MsgType"]
    user_open_id = msg_xml_dict["FromUserName"]
    # 需要回复的信息
    response_dict = {
        "xml": {
            "ToUserName": msg_xml_dict["FromUserName"],
            "FromUserName": msg_xml_dict["ToUserName"],
            "CreateTime": int(time.time()),
            "MsgType": "text",
        }
    }
    # 当msg_type消息类型的值为event时, 表示该消息类型为推送消息, 例如微信用户 关注公众号(subscribe),取消关注(unsubscribe)
    print("消息类型", msg_type)
    if msg_type == "event":
        # 事件推送消息
        msg_event = msg_xml_dict["Event"]
        if msg_event.isdigit():
            # 用户关注公众号, 回复感谢信息
            response_dict["xml"]["Content"] = "感谢您的关注!请输入手机号码与云课堂账户绑定。"
            response_xml_str = xmltodict.unparse(response_dict)
            return response_xml_str
    elif msg_type == "text":
        # 文本消息, 获取消息内容, 用户发送 哈哈, 回复 呵呵
        msg_body = msg_xml_dict["Content"]
        print("正在回复消息")
        # 查询
        msg = _mysqlSelectOne("userId", user_open_id)
        if msg is None:
            # 未注册用户
            if msg_body.isdigit():
                try:
                    _mysqlInsertOne(["userId", "phoneNumber"], [user_open_id, msg_body])
                    response_dict["xml"]["Content"] = "绑定成功(现在还未开发完毕，7月10日版本如果不在钉钉家校通讯录中，将不会成功。)"
                except Exception as e:
                    response_dict["xml"]["Content"] = "绑定异常,请联系管理员：" + str(e)

            else:
                response_dict["xml"]["Content"] = "请输入一个电话号码，由纯数字构成，前后不要加符号和其他文字。"

        else:
            # 已注册用户
            response_dict["xml"]["Content"] = "欢迎您，绑定用户{},您的当前学习情况是:\n" \
                                              "学习总课时:0\n昨日学习课时:0\n学习状态:正常\n" \
                                              "（现在还未开发完毕，7月10日版本会显示当前学生状态）".format(msg["phoneNumber"])
        response_xml_str = xmltodict.unparse(response_dict)
        return response_xml_str
    # 其他一律回复 success
    return "success"


def access_token():
    global ACCESS_TOKEN
    try:
        print("正在更新access_token")
        res = requests.get(
            "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}".format(APP_ID,
                                                                                                             APP_SECRET))
        text = res.text
        jsonObj = json.loads(text)
        print("成功更新access_token!", jsonObj['access_token'])
        ACCESS_TOKEN = jsonObj['access_token']
        return jsonObj['access_token']
    except:
        traceback.print_exc()
        return None


def wechat(request):
    if request.method == 'GET':
        data = _getArguments(request)
        print("收到wechat注册请求", data)
        return HttpResponse(data['echostr'])
    if request.method == 'POST':
        print("收到一个需要响应的消息体请求")
        msg = messageHelper(request)
        print("准备返回", msg)
        return HttpResponse(msg)


def _getArguments(request):
    if request.method == 'GET':
        print("收到GET请求")
        arguments = dict(request.GET)
        for arg in arguments:
            if type(arguments[arg]) == type([]):
                arguments[arg] = arguments[arg][0]
    else:
        print("收到POST请求")
        print("post-body")
        print(request.body.decode())
        arguments = json.loads(request.body.decode())
    return arguments


def _mysqlSelectOne(key, value):
    # 创建游标 默认元祖
    # cursor = conn.cursor()
    # 游标设置为字典
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    # 执行函数  返回受影响的函数
    effect_rows = cursor.execute("select * from public_user where {}='{}' limit 1 ".format(key, value))
    # #获取前一条数据
    # print(cursor.fetchone())
    # #获取前N条数据
    # print(cursor.fetchmany(2))
    # 获取全部数据
    data = cursor.fetchall()
    conn.commit()
    # 关闭游标
    cursor.close()
    if len(data) == 0:
        return None
    else:
        return data[0]


def _mysqlInsertOne(keys, datas):
    # 创建游标
    cursor = conn.cursor()
    # 执行函数  返回受影响的函数
    keysStr = ""
    for key in keys:
        keysStr += key + ","
    keysStr = keysStr[0:len(keysStr) - 1]
    datasStr = ""
    for data in datas:
        datasStr += "'" + data + "',"
    datasStr = datasStr[0:len(datasStr) - 1]

    effect_rows = cursor.execute("insert into public_user({}) values({})".format(keysStr, datasStr))
    print("受影响的行数", effect_rows)
    conn.commit()
    # 关闭游标
    cursor.close()
    return effect_rows


threading.Timer(60 * 5, access_token, args=()).start()
if __name__ == '__main__':
    try:
        print(_mysqlInsertOne(["userId", "phoneNumber"], ["test2", "16607550002"]))
    except Exception as e:
        print(e)
    print(_mysqlSelectOne("userId", "test"))
